package com.hx0311.pas.security.user.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.hx0311.core.dao.BaseDao;
import com.hx0311.core.dao.support.ResultSetUtil;
import com.hx0311.pas.security.user.model.User;

public class UserDao extends BaseDao {
	
	private Connection conn;
	private PreparedStatement stat;

	public void add(User user) {
		if (user != null) {
			String sql = "insert into xcryglb (xcrbh, xm, mm, rylb, jgm) values (?, ?, ?, ?, ?)";
			try {
				conn = getConnection();
				stat = conn.prepareStatement(sql);
				stat.setString(1, user.getXcrbh());
				stat.setString(2, user.getXm());
				stat.setString(3, user.getMm());
				stat.setString(4, user.getRylb());
				stat.setString(5, user.getJgm());
				stat.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				close(stat, conn);
			}
		}
	}

	public void update(User user) {
		if (user != null) {
			String sql = "update xcryglb set xm = ?, mm = ?, rylb = ?, jgm = ? where xcrbh = ?";
			try {
				conn = getConnection();
				stat = conn.prepareStatement(sql);
				stat.setString(1, user.getXm());
				stat.setString(2, user.getMm());
				stat.setString(3, user.getRylb());
				stat.setString(4, user.getJgm());
				stat.setString(5, user.getXcrbh());
				stat.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				close(stat, conn);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public List getAll() {
		String sql = "select xcrbh, xm, mm, rylb, jgm from xcryglb";
		ResultSet rs = null;
		try {
			conn = getConnection();
			stat = conn.prepareStatement(sql);
			rs = stat.executeQuery();
			return ResultSetUtil.toList(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(rs, stat, conn);
		}
		return java.util.Collections.EMPTY_LIST;
	}
	
	/**
	 * 根据用户名密码检索用户
	 * @param xm
	 * @param mm
	 * @return
	 */
	public User getUser(String xcrbh, String mm){
		String sql = "select xcrbh, xm, mm, rylb, jgm from xcryglb where xcrbh = ? and mm = ?";
		ResultSet rs = null;
		try {
			conn = getConnection();
			stat = conn.prepareStatement(sql);
			stat.setString(1, xcrbh);
			stat.setString(2, mm);
			rs = stat.executeQuery();
			if (rs.next()){
				User user = new User();
				return (User) ResultSetUtil.toObject(user, rs);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(rs, stat, conn);
		}
		return null;
	}

	@Override
	public String getIdName() {
		return "xcrbh";
	}

	@Override
	public String getTableName() {
		return "xcryglb";
	}

}
